<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['sa:fiscalYear:add']" @click="openDialog(null)">增加</el-button>
          <!-- <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['sa:fiscalYear:export']" @click="exportHandler">导出</el-button> -->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      v-horizontal-scroll="'auto'"
      highlight-current-row
      max-height="740"
      v-loading="loading"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      />
      <el-table-column
        property="year"
        label="财年"
        align="center"
        width="80"
      />
      <el-table-column
        label="财年范围"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.startDate">
            {{ scope.row.startDate.slice(0,7) }} - {{ endDateHandler(scope.row.endDate).slice(0,7) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="第一季度范围"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.firstStartDate">
            {{ scope.row.firstStartDate.slice(0,7) }} - {{ endDateHandler(scope.row.firstEndDate).slice(0,7) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="第二季度范围"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.secondStartDate">
            {{ scope.row.secondStartDate.slice(0,7) }} - {{ endDateHandler(scope.row.secondEndDate).slice(0,7) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="第三季度范围"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.thirdStartDate">
            {{ scope.row.thirdStartDate.slice(0,7) }} - {{ endDateHandler(scope.row.thirdEndDate).slice(0,7) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="第四季度范围"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.fourthStartDate">
            {{ scope.row.fourthStartDate.slice(0,7) }} - {{ endDateHandler(scope.row.fourthEndDate).slice(0,7) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
        width="100"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        width="160"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('sa:fiscalYear:edit') || $auth.hasPermi('sa:fiscalYear:remove')"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['sa:fiscalYear:edit']" @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['sa:fiscalYear:remove']" type="text" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="500px"
      :fullscreen="device =='mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="demo-form" :label-position="device =='mobile' ? 'top' : 'right'">
        <el-form-item label="财年" prop="year">
          <el-date-picker
            v-model="form.year"
            type="year"
            placeholder="请选择财年"
            value-format="yyyy"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="财年范围" prop="startDate">
          <el-date-picker
            v-model="yearData"
            type="monthrange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第一季度范围" prop="firstStartDate">
          <el-date-picker
            v-model="firstData"
            type="monthrange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第二季度范围" prop="secondStartDate">
          <el-date-picker
            v-model="secondData"
            type="monthrange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第三季度范围" prop="thirdStartDate">
          <el-date-picker
            v-model="thirdData"
            type="monthrange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第四季度范围" prop="fourthStartDate">
          <el-date-picker
            v-model="fourthData"
            type="monthrange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/sa/fiscalYear";
import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import { mapGetters } from 'vuex'

export default {
  name: 'FiscalYearView',
  dicts: ['sys_activity_type'],
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 活动日期
      activityDate: [],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      yearData: [], // 财年范围
      firstData: [], // 第一季度范围
      secondData: [], // 第二季度范围
      thirdData: [], // 第三季度范围
      fourthData: [], // 第四季度范围
      // 新增和修改参数
      form: {
        year: "", // 年份
        startDate: "",
        endDate: "",
        firstStartDate: "",
        firstEndDate: "",
        secondStartDate: "",
        secondEndDate: "",
        thirdStartDate: "",
        thirdEndDate: "",
        fourthStartDate: "",
        fourthEndDate: "",
        remark: "",
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        startDate: [
          {required: true, message: '请选择财年范围', trigger: 'change'}
        ],
        // firstStartDate: [
        //   {required: true, message: '请选择第一季度日期范围', trigger: 'change'}
        // ],
        // secondStartDate: [
        //   {required: true, message: '请选择第二季度日期范围', trigger: 'change'}
        // ],
        // thirdStartDate: [
        //   {required: true, message: '请选择第三季度日期范围', trigger: 'change'}
        // ],
        // fourthStartDate: [
        //   {required: true, message: '请选择第四季度日期范围', trigger: 'change'}
        // ],
        year: [
          {required: true, message: '请选择财年', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请选择省份', trigger: 'change'}
        ],
        activityDate: [
          {required: true, message: '请选择日期', trigger: 'change'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  watch: {
    yearData: {
      handler(newV) {
        let startData = ''
        let endData = ''
        if(newV) {
          endData = this.handleStartDateChange(newV)
          startData = newV[0]
        } else {
          startData = ''
          endData = ''
        }
        this.form.startDate = startData
        this.form.endDate = endData
      }
    },
    firstData: {
      handler(newV) {
        let startData = ''
        let endData = ''
        if(newV) {
          endData = this.handleStartDateChange(newV)
          startData = newV[0]
        } else {
          startData = ''
          endData = ''
        }
        this.form.firstStartDate = startData
        this.form.firstEndDate = endData
      }
    },
    secondData: {
      handler(newV) {
        let startData = ''
        let endData = ''
        if(newV) {
          endData = this.handleStartDateChange(newV)
          startData = newV[0]
        } else {
          startData = ''
          endData = ''
        }
        this.form.secondStartDate = startData
        this.form.secondEndDate = endData
      }
    },
    thirdData: {
      handler(newV) {
        let startData = ''
        let endData = ''
        if(newV) {
          endData = this.handleStartDateChange(newV)
          startData = newV[0]
        } else {
          startData = ''
          endData = ''
        }
        this.form.thirdStartDate = startData
        this.form.thirdEndDate = endData
      }
    },
    fourthData: {
      handler(newV) {
        let startData = ''
        let endData = ''
        if(newV) {
          endData = this.handleStartDateChange(newV)
          startData = newV[0]
        } else {
          startData = ''
          endData = ''
        }
        this.form.fourthStartDate = startData
        this.form.fourthEndDate = endData
      }
    },
    activityDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
  },
  activated() {
    this.getList()
  },
  methods: {
    handleStartDateChange(val) {
      if (val) {
        const [start, end] = val
        let resYear = ''
        let resMonth = ''
        const [year, month, day] = end.split('-');
        const nextMonth = (parseInt(month, 10) + 1); // 获取下一个月，并确保是两位数
        resYear = nextMonth > 12 ? +year + 1 : year
        resMonth = nextMonth > 12 ? (nextMonth - 12).toString().padStart(2, '0') : nextMonth

        return `${resYear}-${resMonth}-${day}`
      } else {
        return '' // 如果开始日期为空，则结束日期也为空
      }
    },
    endDateHandler(dateStr) {
      if(!dateStr) return ''
      // 格式验证
      if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
        throw new Error('Invalid date format, expected YYYY-MM-DD')
      }

      // 结构分解
      const parts = dateStr.split('-')
      let year = parseInt(parts[0])
      let month = parseInt(parts[1])

      // 数值校验
      if (year < 1970 || month < 1 || month > 12) {
        throw new Error('Invalid date value')
      }

      // 计算逻辑
      month -= 1
      if (month === 0) {
        year -= 1
        month = 12
      }

      // 结果构造
      return [
        year.toString(),
        month.toString().padStart(2, '0'),
        '01'
      ].join('-')
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = { ...row }
        this.yearData = [ this.form.startDate, this.endDateHandler(this.form.endDate) ]
        this.firstData = this.form.fourthStartDate ? [ this.form.firstStartDate, this.endDateHandler(this.form.firstEndDate) ] : null
        this.secondData = this.form.secondStartDate ? [ this.form.secondStartDate, this.endDateHandler(this.form.secondEndDate) ] : null
        this.thirdData = this.form.thirdStartDate ? [ this.form.thirdStartDate, this.endDateHandler(this.form.thirdEndDate) ] : null
        this.fourthData = this.form.fourthStartDate ? [ this.form.fourthStartDate, this.endDateHandler(this.form.fourthEndDate) ] : null

        this.dialogTitle = 2
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
          this.yearData = null
          this.firstData = null
          this.secondData = null
          this.thirdData = null
          this.fourthData = null
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/province/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `year_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if(this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.activityDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">

</style>
